/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package database.entitymanager;

import database.entity.Action;
import database.entitymanager.exceptions.NonexistentEntityException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import database.entity.ShopItem;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Stefan
 */
public class ActionManager {

 
    private static EntityManagerFactory emf = EntityFactoryHolder.getInstance();

    public static EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public static void create(Action action) {
        if (action.getShopItemList() == null) {
            action.setShopItemList(new ArrayList<ShopItem>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<ShopItem> attachedShopItemList = new ArrayList<ShopItem>();
            for (ShopItem shopItemListShopItemToAttach : action.getShopItemList()) {
                shopItemListShopItemToAttach = em.getReference(shopItemListShopItemToAttach.getClass(), shopItemListShopItemToAttach.getItemid());
                attachedShopItemList.add(shopItemListShopItemToAttach);
            }
            action.setShopItemList(attachedShopItemList);
            em.persist(action);
            for (ShopItem shopItemListShopItem : action.getShopItemList()) {
                shopItemListShopItem.getActionList().add(action);
                shopItemListShopItem = em.merge(shopItemListShopItem);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static void edit(Action action) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Action persistentAction = em.find(Action.class, action.getActionid());
            List<ShopItem> shopItemListOld = persistentAction.getShopItemList();
            List<ShopItem> shopItemListNew = action.getShopItemList();
            List<ShopItem> attachedShopItemListNew = new ArrayList<ShopItem>();
            for (ShopItem shopItemListNewShopItemToAttach : shopItemListNew) {
                shopItemListNewShopItemToAttach = em.getReference(shopItemListNewShopItemToAttach.getClass(), shopItemListNewShopItemToAttach.getItemid());
                attachedShopItemListNew.add(shopItemListNewShopItemToAttach);
            }
            shopItemListNew = attachedShopItemListNew;
            action.setShopItemList(shopItemListNew);
            action = em.merge(action);
            for (ShopItem shopItemListOldShopItem : shopItemListOld) {
                if (!shopItemListNew.contains(shopItemListOldShopItem)) {
                    shopItemListOldShopItem.getActionList().remove(action);
                    shopItemListOldShopItem = em.merge(shopItemListOldShopItem);
                }
            }
            for (ShopItem shopItemListNewShopItem : shopItemListNew) {
                if (!shopItemListOld.contains(shopItemListNewShopItem)) {
                    shopItemListNewShopItem.getActionList().add(action);
                    shopItemListNewShopItem = em.merge(shopItemListNewShopItem);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = action.getActionid();
                if (findAction(id) == null) {
                    throw new NonexistentEntityException("The action with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Action action;
            try {
                action = em.getReference(Action.class, id);
                action.getActionid();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The action with id " + id + " no longer exists.", enfe);
            }
            List<ShopItem> shopItemList = action.getShopItemList();
            for (ShopItem shopItemListShopItem : shopItemList) {
                shopItemListShopItem.getActionList().remove(action);
                shopItemListShopItem = em.merge(shopItemListShopItem);
            }
            em.remove(action);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static List<Action> findActionEntities() {
        return findActionEntities(true, -1, -1);
    }

    public static List<Action> findActionEntities(int maxResults, int firstResult) {
        return findActionEntities(false, maxResults, firstResult);
    }

    private static List<Action> findActionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Action.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public static Action findAction(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Action.class, id);
        } finally {
            em.close();
        }
    }

    public static int getActionCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Action> rt = cq.from(Action.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
